﻿function Invoke-TSMCommand {    
    <#
        .SYNOPSIS
            Invoke command against TSM
                    
        .DESCRIPTION
            The Invoke-TSMCommand function executes the specified command against the TSM server
        
        .PARAMETER Command
            The command to execute

        .EXAMPLE
            Invoke-TSMCommand -Command "query process"

        .NOTES
            Contributors:  David Seibel
            Last Revision Date: 09/15/2015

    #>
    [CmdletBinding()]
    Param(
        [Parameter(Position=0,Mandatory=$true)]
        [string]$Command
    )

    if ((Get-Variable TSMCredential -ErrorAction SilentlyContinue) -eq $null) {
        throw "TSM credentials not found! Reauthenticate using 'Connect-TSMServer'."
    }

    $dsmadmc = ".\dsmadmc.exe"
    $user = "-id=$($TSMCredential.Username)"
    $pass = "-password=$($TSMCredential.GetNetworkCredential().Password)"
    $displayargs = "-dataonly=yes -displaymode=list"
    $fullcmd = "$dsmadmc $user $pass $displayargs ""$Command"""
    Write-Verbose "Executing command '$fullcmd'"

    if ((Get-PSSession | Where-Object {($_.ComputerName -eq $TSMServer) -and ($_.State -eq "Opened")}) -eq $null) {
        throw "An open PSSession with the TSM server was not found!"
    }

    Invoke-Command -ScriptBlock { param($command) Invoke-Expression $command } -ArgumentList $fullcmd -Session $TSMSession -OutVariable TSMoutput | Out-Null
    return $TSMoutput
}